import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) { // 如果vuex里的token存在那么注入到请求投中
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 因为请求参数传错,后台http状态码也返回200 所以在拦截器里面进行处理异常 通过响应信息内容判断对错
    const { success, message, data } = response.data
    if (success) {
      // 请求参数正确 给页面返数据
      return data
    } else {
      // 请求参数错误 ===> 抛出错误 ===>组件调用接口 通过trycatch捕获 响应错误信息
      // 用element组件的Message消息提示错误
      Message({
        message: message,
        type: 'error',
        duration: 2 * 1000
      })
      // return Promise.reject('请求出错: ', message)
      // 手动触发reject 要创建一个错误并抛出
      return Promise.reject(new Error('请求出错: ', message))
    }
  },
  async error => {
    // 200开外的错误状态码的处理位置
    console.dir(error)
    /**
     * 出现401情况===>重新登录
     * 解决
     * 1.先判断状态码为401
     * 2.退出登录
     * 3.删除用户信息
     * 4.带上出现401的页面redirect返回登录页,登录成功好进行回跳
     */
    if (error.response && error.response.status === 401) {
      // 避免页面多次请求出现多次401状况===>导致重复跳转登录页面: 造成重新登录后不能正确跳转到上次访问的页面
      if (router.currentRoute.path === '/login') return

      //  删除vuex里的信息
      await store.dispatch('user/logout')
      // 消息提示
      Message({
        message: error.response.data.message,
        type: 'error',
        duration: 3 * 1000
      })
      // 跳转登录页
      router.replace(`/login?redirect=${router.currentRoute.path}`)
    }

    return Promise.reject(error)
  }
)

export default service
